package com.levi.stream;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * @author shentong
 * @date 2022/1/11 9:00 PM
 * @description
 */
public class DemoReduce {
    public static void main(String[] args) throws IOException {
        List<Integer> numbers = new ArrayList<Integer>() {{
            add(1);
            add(2);
            add(3);
            add(4);
            add(5);
            add(6);
        }};
        Integer reduce = numbers.stream().reduce(0, Integer::sum);
        System.out.println(reduce);
        Optional<Integer> option = numbers.stream().reduce(Integer::sum);
        if (option.isPresent()) {
            Integer result = option.get();
            System.out.println(result);
        }

        //  max  min
        Optional<Integer> min = numbers.stream().min(Integer::compareTo);
        if (min.isPresent()) {
            Integer minNum = min.get();
            System.out.println(minNum);
        }
        Optional<Integer> max = numbers.stream().max(Integer::compareTo);
        if (max.isPresent()) {
            Integer maxNum = max.get();
            System.out.println(maxNum);
        }

        System.out.println("---------------------------");
        //通过文件创建stream流
        String dir = "/Users/shentong/test";
        //读取目录  获取目录下的文件集合流
        Stream<Path> pathStream = Files.list(Paths.get(dir));
        pathStream.forEach(path-> {
            System.out.println(path);
                    try {
                        //读取每个文件内容 转换成stream流
                        Stream<String> lines = Files.lines(path);
                        lines.forEach(System.out::println);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        );
    }
}
